package com.deltabot.master.masterservers;

import com.deltabot.master.heartbeatserver.cache;

import java.awt.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import static java.lang.Thread.sleep;

public class queryIW4servers{


    public static void initQuery(List<String> serverList){

        for(String server : serverList){

             Query(server.split(":")[0], Integer.parseInt(server.split(":")[1]));

        }

    }

    private static void Query(String IP, int port){

       // System.out.println("Querying " + IP + ":" + port);

        byte[] PACKER_HEADER = new byte[] { (byte) 0xFF, (byte) 0xFF,
                (byte) 0xFF, (byte) 0xFF };

        try {
            InetAddress serveraddress = InetAddress.getByName(IP);

            DatagramSocket socket = new DatagramSocket();
            socket.setSoTimeout(200);
            socket.connect(serveraddress, port);
            byte[] fin = new byte[300];
            byte[] data = "getstatus".getBytes();
            System.arraycopy(PACKER_HEADER, 0, fin, 0, PACKER_HEADER.length);
            System.arraycopy(data, 0, fin, PACKER_HEADER.length, data.length);
            DatagramPacket output = new DatagramPacket(fin, fin.length,
                    serveraddress, port);
            socket.send(output);
            byte[] buffer = new byte[65565];
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            socket.receive(dp);
            socket.close();
            String s = new String(dp.getData(), 0, dp.getLength());
            s = s.replace("����statusResponse\n", "");

            List<String> serverVariables = parseData(s);

            //Some dummy data, incase we can't get certain things from the
            String Hostname = "null";
            String Map = "mp_default";
            String currentPlayers = "0";
            String MaxPlayers = "0";
            String Game = "null";
            String GameType = "null";
            String HardCore = "NO";
            String Country = "null";

        for (String var: serverVariables){
           // System.out.println(var.split("¶")[0] + ":" + var.split("¶")[1]);
            if(var.startsWith("sv_hostname")){
                Hostname = var.split("¶")[1];
            }

            if(var.startsWith("_Location")){
               Country = var.split("¶")[1];
            }

            if(var.startsWith("mapname")){
               Map = var.split("¶")[1];
            }

            if(var.startsWith("DB:CURRENTPLAYERS")){
                currentPlayers = var.split("¶")[1];

            }

            if(var.startsWith("sv_maxclients")){
                MaxPlayers = var.split("¶")[1];

            }
            if(var.startsWith("gamename")){
                Game = var.split("¶")[1];

            }

            if(var.startsWith("g_gametype")){
                GameType = var.split("¶")[1];

            }

            if(var.startsWith("g_hardcore")){
                HardCore = var.split("¶")[1];

                if(HardCore == "1"){
                    HardCore = "YES";
                } else {
                    HardCore = "NO";
                }

            }

        }

            if (Game.equals("Call of Duty 4")){
                Game = "MW";
            }
            if (Game.equals("IW4")){
               Game = "MW2";
            }
            if (Game.equals("IW5")){
                Game = "MW3";
            }
            if (Game.equals("T5")){
                Game = "BO";
            }
            if(!(Hostname.equals("null"))){
                cache.addServer(Hostname, IP, String.valueOf(port), Map, currentPlayers, MaxPlayers, Game, GameType, "NO", HardCore, Country);
            }
        } catch (SocketException e) {
          //  e.printStackTrace();
          //  System.out.println("Error while querying server");
        } catch (IOException e) {
           // e.printStackTrace();
            //System.out.println("Error while querying server");
        }
    }


    public static List<String> parseData(String Data){

        List<String> parsedData = new ArrayList<String>();
        String splitted[] = Data.split("\n");
        String variables = splitted[0];
        String Players = "0";

        if(splitted.length > 1){
            // If > 1, players are in the server
            Players = String.valueOf(splitted.length - 1);
        }

         String splittedVariables[] = variables.split("\\\\");

        int odd = 1;
        int even = 2;

        while(even <= splittedVariables.length){

            parsedData.add(splittedVariables[odd] + "¶" + splittedVariables[even]);
            odd += 2;
            even += 2;
        }

        parsedData.add("DB:CURRENTPLAYERS¶" + Players);

        return parsedData;

    }


}
